<?php
// Needs some cleanup

/**
 * PARENT INFORMER: Joseph Betansos, Carl Dizon, Karlo Garcia,
 *                  Aljero Jimenez, Ronaldo Sales
 * @date: 2/17/2011
 *
 * @parserecds.php
 *
 * This PHP file contains file and display functions. It also processes CSV files that
 * include academic grades of students and enables it to edit them (for administrators).
 *
 * The Parent Informer uses MySQL to assign privileges to its
 * users. Privilege levels were assigned to each user depending
 * on the range of access to the academic student records. As
 * the privilege level increases, the limited the range of access
 * to the records the user has.
 *
 * PRIVILEGE LEVELS (in MySQL. Assigned to $info['priv'] -> $thepriv):
 *
 * PRIV 1: Superuser/Administrator (PRINCIPAL, ADVISERS)
 * PRIV 2: Academic TEACHERS
 * PRIV 3: STUDENTS
 */

// Define constants used throughout the code
define("FRSTYRURL", "../mail/parentmail.php?yrlvl=frst");
define("SECNDYRURL", "../mail/parentmail.php?yrlvl=secnd");
define("THRDYRURL", "../mail/parentmail.php?yrlvl=thrd");
define("FRTHYRURL", "../mail/parentmail.php?yrlvl=frth");
define("NAMES", "<tr>\n<th>LAST NAME</th>\n<th>FIRST NAME</th>\n<th>MIDDLE NAME</th>\n");

Class ProcGrades {

	function __construct() {
		// Load configuration XML file
		$conffile = "../xml/acadconf.xml";
		$this->xmlconf = simplexml_load_file($conffile) or die('<br>Unable to load configurations.');
		$this->presyr = strstr($this->xmlconf->syr, '-', true);

		// Load XML subjects list
		$fileto = "../xml/subjects.xml";
		$this->xmlsubj = simplexml_load_file($fileto) or die('<br>Unable to load subjects list.');
	}

	/**
	 * This function executes necessary actions
	 * for displaying academic records of
	 * students depending on the privilege of the
	 * user and the year level he/she selected in
	 * the selection screen.
	 *
	 * This function retrieves student records whose
	 * year encompasses June to December. For instance,
	 * if today is AY 2011-2012, the statement retrieves
	 * grades with the suffix "2011" and not "2012" even
	 * if the year changes from 2011 to 2012. The academic
	 * year can be set through acadconf.xml.
	 */
	function dispRecds($thepriv, $yrlvl, $subjdept) {

		switch($thepriv) {

			/*
			 * If the user is an administrator, display all grades of students
			 * in one big table encompassing the whole page. The grades are also
			 * linked to parentmail.php which makes automated e-mail notifications
			 * about the academic performance of thir child/ren according to the
			 * format given by the user in the settings. 
			 */
			case 1:

				if(!($thequery = mysql_query("SELECT * FROM ".$yrlvl."yr".$this->presyr." ORDER BY lnm ASC"))) {
					echo "<br><br>Unable to retrieve student names. Please try again later<br>\n";
					echo "or inform the school if the problem persists.<br><br>\n";
					break;
				}

				if(mysql_num_rows($thequery)!=0) {
					echo "<br>For SY ".$this->xmlconf->syr.".";
					$theurl = strtoupper($yrlvl) ."YRURL";

					echo "<br><br>\n";

					// Open grades CSV file
					if(!($recdtoopen = @fopen("csv/".$yrlvl."yr".$this->presyr.".csv", "r"))) {
						echo "Unable to retrieve student grades. Please try again later<br>\n";
						echo "or inform the school administration if the problem persists.<br><br>\n";
						break;
					}
					$prntgr = fgetcsv($recdtoopen, 1024);

					echo "<table class='tablerecd'>\n";
					echo constant("NAMES");

					/*
					* The for block below iterates through the subjects written
					* in the XML list of subjects. However, it uses the alias of
					* each instead of the full names to save space.
					*/
					for($subji=1;$subji<=count($this->xmlsubj->xpath('//year[@level="'.$yrlvl.'"]/name'));$subji++) {
						$crseach = $this->xmlsubj->xpath('//year[@level="'.$yrlvl.'"]/name['.$subji.']/@abbr');
						echo "<th>".$crseach[0]."</th>\n";
						//echo "<th>".$prntgr[$subji]."</th>\n";
					}

					echo "</tr>\n\n";

					while(($row = mysql_fetch_array($thequery)) && !feof($recdtoopen)) {
						echo "<tr>\n";
						echo "<td>$row[2]</td>\n";
						echo "<td>$row[3]</td>\n";
						echo "<td>$row[4]</td>\n";
						$prntgr = fgetcsv($recdtoopen, 1024);
						for($cnt=3;$cnt<=count($prntgr)-1;$cnt++) {
							echo "<td><a href='".constant($theurl)."&amp;id=".$row[0]."&amp;subj=".($cnt-2)."'>".$prntgr[$cnt]."</a></td>\n";
						}
						echo "</tr>\n\n";
					} 
					echo "</table>\n<br>";

					// Close the CSV file.
					fclose($recdtoopen);
				}
				else {
					echo "<br><br>No existing records for this school year ".$this->xmlconf->syr.".</br>";
				}

			break;

			/*
			 * If the user is a teacher, display grades only to his/her subject area.
			 * Similar to having an administrator privilege, grades are also linked to
			 * parentmail.php.
			 *
			 * The code utilizes both MySQL and CSV to display student names and
			 * grades respectively.
			 */
			case 2:

				// Initialize array of year level codes
				$yrs = array('frst', 'secnd', 'thrd', 'frth');

				/* 
				* Separate multiple subjects into arrays provided that
				* it is comma-separated
				*/
				$subjdepts = explode(',', $subjdept);

				// Display tabs
				echo "<ol id='tabs'>\n";
				for($x=0;$x<=count($subjdepts)-1;$x++) {
					echo "<li><a href='#s".$x."'><span>".$subjdepts[$x]."</span></a></li>\n";
				}
				echo "</ol>\n\n";

				/**
				 * Iterators:
				 *
				 * This code uses iterators to display the correct grades for
				 * each subject to its respective tabs. The iterators are:
				 *
				 * > $tabindex (below) - this iterator increments if the code has
				 *						 matched the subject department of the teacher,
				 *						 subjects listed in the XML file, and the year
				 *						 level where the subject is. It represents the
				 *						 tab index of the grades for the subject.
				 * > $arryr - this iterator increments if the code has finished iterating
				 *			  through the subjects present in a year level. It represents
				 *			  the year level where the code is reading and resets to 0 once
				 *			  it has parsed the grades for a subject.
				 * > $subjcnt - this iterator increments for every subject it encounters and
				 *				resets to 1 once it changes to another year level (dependent on
				 *				$arryr).
				 */
				$tabindex = 0;

				/*
				 * The foreach function and succeeding loops display the
				 * grades of students according to the subject department
				 * the teacher has written in its settings.
				 *
				 * The first foreach loop (below) iterates through the
				 * subject department of the teacher
				 */
				foreach($subjdepts as $toteach) {
					$arryr = 0;

					while($arryr<4) {
						$subjcnt = 1;
						foreach($this->xmlsubj->xpath('//year[@level=\''.$yrs[$arryr].'\']/name') as $subjtxt) {
							if(trim($toteach) == $subjtxt) {

								// Retrieve student names stored in MySQL
								if(!($thequery = mysql_query("SELECT * FROM ".$yrs[$arryr]."yr".$this->presyr." ORDER BY lnm ASC"))) {
									echo "<div class='tabcontent' id='s".$tabindex."'>\n";
									echo "Student names cannot be retrieved. Please try again later<br>\n";
									echo "or inform the school if the problem persists.\n";
									echo "</div>\n\n";
									$tabindex++;
									break;
								}

								// Open CSV grades
								if(!($recdtoopen = @fopen("csv/".$yrs[$arryr]."yr".$this->presyr.".csv", "r"))) {
									echo "<div class='tabcontent' id='s".$tabindex."'>\n";
									echo "CSV student grades cannot be retrieved. Please try again later<br>\n";
									echo "or inform the school if the problem persists.\n";
									echo "</div>\n\n";
									$tabindex++;
									break;
								}
								$prntgr = fgetcsv($recdtoopen, 1024);

								echo "<div class='tabcontent' id='s".$tabindex."'>\n";
								echo "<b>".$subjtxt."</b><br>\n";
								echo "SY ".$this->xmlconf->syr."\n<br><br>\n";
								echo "<table class='tablerecd'>\n";
								$theurl = strtoupper($yrs[$arryr]) ."YRURL";

								echo constant("NAMES");
								echo "<th>FINAL GRADE</th>\n</tr>\n\n";

								while(($row = mysql_fetch_array($thequery)) && !feof($recdtoopen)) {
									echo "<tr>\n";
									echo "<td>$row[2]</td>\n";
									echo "<td>$row[3]</td>\n";
									echo "<td>$row[4]</td>\n";
									$prntgr = fgetcsv($recdtoopen, 1024);

									echo "<td><a href='".constant($theurl)."&amp;id=".$row[0]."&amp;subj=".($subjcnt)."'>".$prntgr[$subjcnt+2]."</a></td>\n";
									echo "</tr>\n\n";
								}

								$tabindex++;
								echo "</table>\n</div>\n\n";
							}
							$subjcnt++;
						}
						$arryr++;
					}
				}

				echo "<script type='text/javascript' src='../../jsc/tabswitch.js'></script>\n";
				echo "<script type='text/javascript'>\n";
				echo "activatables('subject', [";

				for($tct=0;$tct<=count($subjdepts)-1;$tct++) {
					echo "'s".$tct."'";
					if($tct<=count($subjdepts)-2) {
						echo ", ";
					}
				}
				echo "]);\n</script>\n\n";

				// Close the CSV file.
				fclose($recdtoopen);

			break;

			/**
			 * If the user is a student, redirect him/her to his/her grades.
			 */
			case 3:
				header("Location: index.php");
			break;
			
			default:
				echo "<br><br>Sorry. Cannot retrieve CSV grades. Please try again later<br>";
				echo "or inform the school if the problem persists.";
		} // END OF switch
	} // END OF FUNCTION dispRecds

	/**
	 * The function editRecds resembles the function dispRecds above. However,
	 * text is converted into input boxes. For the sake of clarity, the comments
	 * written in dispRecds above are retained here.
	 */
	function editRecds($priv, $subjdept) {

		// Load XML subjects list
		$fileto = "../xml/subjects.xml";
		$xmlsubj = simplexml_load_file($fileto) or die('<br>Unable to load subjects list.');

		switch($priv) {
			case 1:
				echo "<br>FOR TESTING... xD";
			break;

			case 2:
				// Initialize array of year level codes
				$yrs = array('frst', 'secnd', 'thrd', 'frth');

				/**
				 * Separate multiple subjects into arrays provided that
				 * it is comma-separated
				 */
				$subjdepts = explode(',', $subjdept);

				// Display tabs
				echo "<ol id='tabs'>\n";
				for($x=0;$x<=count($subjdepts)-1;$x++) {
					echo "<li><a href='#s".$x."'><span>".$subjdepts[$x]."</span></a></li>\n";
				}
				echo "</ol>\n\n";

				/**
				 * Iterators:
				 *
				 * This code uses iterators to display the correct grades for
				 * each subject to its respective tabs. The iterators are:
				 *
				 * > $tabindex (below) - this iterator increments if the code has
				 *						 matched the subject department of the teacher,
				 *						 subjects listed in the XML file, and the year
				 *						 level where the subject is. It represents the
				 *						 tab index of the grades for the subject.
				 * > $arryr - this iterator increments if the code has finished iterating
				 *			  through the subjects present in a year level. It represents
				 *			  the year level where the code is reading and resets to 0 once
				 *			  it has parsed the grades for a subject.
				 * > $subjcnt - this iterator increments for every subject it encounters and
				 *				resets to 1 once it changes to another year level (dependent on
				 *				$arryr).
				 */
				$tabindex = 0;

				/**
				 * The foreach function and succeeding loops display the
				 * grades of students according to the subject department
				 * the teacher has written in its settings.
				 *
				 * The first foreach loop (below) iterates through the
				 * subject department of the teacher
				 */
				foreach($subjdepts as $toteach) {
					$arryr = 0;

					while($arryr<4) {
						$subjcnt = 1;
						foreach($this->xmlsubj->xpath('//year[@level=\''.$yrs[$arryr].'\']/name') as $subjtxt) {
							if(trim($toteach) == $subjtxt) {

								// Retrieve student names stored in MySQL
								if(!($thequery = mysql_query("SELECT * FROM ".$yrs[$arryr]."yr".$this->presyr." ORDER BY lnm ASC"))) {
									echo "<div class='tabcontent' id='s".$tabindex."'>\n";
									echo "Student names cannot be retrieved. Please try again later<br>\n";
									echo "or inform the school if the problem persists.\n";
									echo "</div>\n\n";
									$tabindex++;
									break;
								}

								// Open CSV grades
								if(!($recdtoopen = @fopen("csv/".$yrs[$arryr]."yr".$this->presyr.".csv", "r"))) {
									echo "<div class='tabcontent' id='s".$tabindex."'>\n";
									echo "CSV student grades cannot be retrieved. Please try again later<br>\n";
									echo "or inform the school if the problem persists.\n";
									echo "</div>\n\n";
									$tabindex++;
									break;
								}
								$prntgr = fgetcsv($recdtoopen, 1024);

								echo "<div class='tabcontent' id='s".$tabindex."'>\n";
								echo "<b>".$subjtxt."</b><br>\n";
								echo "SY ".$this->xmlconf->syr."\n<br><br>\n";
								echo "<form action='savegr.php' method=post id='stbl".$tabindex."' name='stbl".$tabindex."'>\n\n";
								echo "<table class='tablerecd'>\n";

								echo constant("NAMES");
								echo "<th>FINAL GRADE</th>\n</tr>\n\n";

								while(($row = mysql_fetch_array($thequery)) && !feof($recdtoopen)) {
									echo "<tr>\n";
									echo "<td>$row[2]</td>\n";
									echo "<td>$row[3]</td>\n";
									echo "<td>$row[4]</td>\n";
									$prntgr = fgetcsv($recdtoopen, 1024);

									echo "<td><input type='text' size='5' maxlength='6' name='yr_".$yrs[$arryr]."_subj_".$subjcnt."_id_".$row[0]."' id='yr_".$yrs[$arryr]."_subj_".$subjcnt."_subj_".$row[0]."' value='".$prntgr[$subjcnt+2]."'></td>\n";
									echo "</tr>\n\n";
								}

								echo "</table>\n";

								?>

								<br><input type="submit" value="SAVE DISPLAYED TO NEW FILE" id="snewpart" name="snewpart" onclick="return notifyme('snew', <?php echo "'stbl".$tabindex."', '".$yrs[$arryr]."', '".$subjcnt."'"; ?>);">
								<input type="submit" value="SAVE DISPLAYED AND OVERWRITE" id="sovrpart" name="sovrpart" onclick="return notifyme('sovr', <?php echo "'stbl".$tabindex."', '".$yrs[$arryr]."', '".$subjcnt."'"; ?>);">

								<?php

								echo "</form>\n</div>\n\n";
								$tabindex++;
							}
							$subjcnt++;
						}
						$arryr++;
					}
				}

				echo "<script type='text/javascript' src='../../jsc/tabswitch.js'></script>\n";
				echo "<script type='text/javascript'>\n";
				echo "activatables('subject', [";

				for($tct=0;$tct<=count($subjdepts)-1;$tct++) {
				echo "'s".$tct."'";
				if($tct<=count($subjdepts)-2) {
				echo ", ";
				}
				}
				echo "]);\n</script>\n\n";

				// Close the CSV file.
				fclose($recdtoopen);

			break;

			default:
				echo "<br><br>Sorry. Cannot retrieve CSV grades. Please try again later<br>";
				echo "or inform the school if the problem persists.";
		}
	} // END OF FUNCTION editRecds


	function saveRecds($yrlvl, $filename, $savetype, $grades, $subjdept = NULL) {
		switch($savetype) {

			case "new":
				if($fhand = @fopen('csv/'.$filename.'.csv', 'x')) {

					/**
					 * Initialize arrays for different information. $gradestosave
					 * should contain the submitted grades while $fnms, $lnms, and
					 * $mnms contain the first, last, and middle names of students,
					 * respectively. $tempary is a temporary array used in the for
					 * loop later to associate the names with the grades and $towrite
					 * contains the arrays temporarily dumped into $tempary.
					 */
					$gradestosave = array();
					$fnms = array();
					$lnms = array();
					$mnms = array();
					$tempary = array();
					$towrite = array();

					/*
					* The foreach loop below passes through the $_POST
					* array. If the key found is of format yr_(?)_subj_(?)_id_(?),
					* insert it into the array $gradestosave.
					*/
					foreach($grades as $x => $y) {
						if(preg_match('/^yr_(frst|secnd|thrd|frth)_subj_[0-9]{1,2}_id_[0-9]{1,2}/', $x)) {
							array_push($gradestosave, $y);
						}
					}

					if($dbquery = mysql_query("SELECT * FROM ".$yrlvl."yr".$this->presyr." ORDER BY lnm ASC;")) {

						// Retrieve names and put them in their respective arrays
						while($tempnms = mysql_fetch_array($dbquery)) {
							$fnms[] = $tempnms['fnm'];
							$lnms[] = $tempnms['lnm'];
							$mnms[] = $tempnms['mnm'];
						}

						// Associate the names with their respective grades.
						for($cnt=0;$cnt<count($fnms);$cnt++) {
							$tempary[] = $lnms[$cnt];
							$tempary[] = $fnms[$cnt];
							$tempary[] = $mnms[$cnt];
							$tempary[] = $gradestosave[$cnt];

							array_push($towrite, $tempary);
							$tempary = array();
						}

						// Write the associated array to the CSV file
						foreach($towrite as $flds) {
							fputcsv($fhand, $flds);
						}

						// Close the CSV file.
						if(fclose($fhand)) {
							echo "<form method='post' action='getinter.php' name='filefrm' id='filefrm'>\n";
							echo "<input type='hidden' name='filen' id='filen' value='".$filename."'>\n";
							echo "</form>\n\n";
							echo "Grades were successfully saved to ".$filename.".csv. The file may be<br>\n";
							echo "accessed <a href='javascript:getfile();'>here</a>.\n";
							echo "<br><br>\n";
							echo "To access the created record, account credentials need to be entered.<br>\n";
						}

					}
					else {
						echo "Cannot retrieve student names.<br>";
						break;
					}

				}
				else {
					echo "Cannot create new record. A record with filename ".$filename." may exist.<br>\n";
					echo "Please try to save the record in another name.<br>\n";
				}
			break;

			case "ovr" :

				// Initialize variables
				$gradestosave = array();
				$subjstr = NULL;
				$rowstep = FALSE;
				$idstep = 1;

				// Open the original file and also create a new file
				$fhorig = @fopen('csv/'.$yrlvl.'yr'.$this->presyr.'.csv', 'r');
				$fhtemp = @fopen('csv/~$tmp.csv', 'w');

				/*
				* Iterate over grades and add to a new array $_POST variables
				* that contain edited grades.
				*/
				foreach($grades as $x => $y) {
					if(preg_match('/^yr_(frst|secnd|thrd|frth)_subj_[0-9]{1,2}_id_[0-9]{1,2}/', $x)) {
						$gradestosave[$x] = $y;
						$subjstr = $x;
					}
					unset($x);
				}

				// Get the subject ID using a temporary string
				preg_match('/[0-9]{1,2}(?=_id_)/', $subjstr, $subjid);
				$lnorig = fgetcsv($fhorig);

				while(!feof($fhorig)) {

					/**
					 * Check whether the table headers are already written in the
					 * temporary file.
					 */
					if($rowstep == FALSE) {
						fputcsv($fhtemp, $lnorig);
						$rowstep = TRUE;
					}

					else {
						/**
						 * Overwrite grades to the column. Write the CSV line in
						 * the temporary file.
						 */
						$lnorig[$subjid[0] + 2] = $gradestosave['yr_'.$yrlvl.'_subj_'.$subjid[0].'_id_'.$idstep];
						$idstep = $idstep + 1;
						fputcsv($fhtemp, $lnorig);
					}

					// Read the next CSV line
					$lnorig = fgetcsv($fhorig);
				}

				// Delete original file and rename temporary file to the original one
				fclose($fhorig);
				fclose($fhtemp);
				unlink('csv/'.$yrlvl.'yr'.$this->presyr.'.csv');
				if(rename('csv/~$tmp.csv', 'csv/'.$yrlvl.'yr'.$this->presyr.'.csv')) {
					echo "Grades were successfully saved to the website's database. Edited grades are now<br>\n";
					echo "reflected in the website.<br><br>\n\n";
					echo "<a href='editdb.php'>Return to Editing Records</a><br>\n";
					echo "<a href='../../'>Return to Main Page</a><br>\n";
				}
			break;

		default:
			echo "FOR TESTING! xD";
		} // END OF switch
	} // END OF FUNCTION saveRecds

} // END OF CLASS ProcGrades

?>